package com.hmdp.aop;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.OperateLog;
import com.hmdp.mapper.OperateLogMapper;
import com.hmdp.utils.UserHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

/**
 * @author tttshaoqi
 * &#064;create 2025-08-01-21:29
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.hmdp.annotation.Log)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable{
        OperateLog operateLog = new OperateLog();
        // 获取操作用户
        UserDTO user = UserHolder.getUser();
        Long id = user.getId();
        operateLog.setOperateUser(id.intValue());
        // 获取操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        // 获取类名
        String className = joinPoint.getTarget().getClass().getName();
        operateLog.setClassName(className);
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        operateLog.setMethodName(methodName);
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        operateLog.setMethodParams(Arrays.toString(args));
        // 获取返回值
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        String jsonStr = JSONUtil.toJsonStr(result);
        operateLog.setReturnValue(jsonStr);
        // 获取运行时间
        long time = end - begin;
        operateLog.setCostTime(time);

        operateLogMapper.insert(operateLog);

        return result;
    }
}
